import { _decorator, Button, Color, director, Label, Node, Sprite, tween, UITransform, v3 } from 'cc';
import { BasePopUp } from '../../../A-FRAME/component/ui.pop-up';
import { GameData } from '../../../Data/GameData';
import { UserData } from '../../../Data/UserData';
import { AudioMgr } from '../../../Mgr/AudioMgr';
import { GameMgr } from '../../../Mgr/GameMgr';
import { UIMgr } from '../../../Mgr/UIMgr';
import LocalizedLabel from '../../../Tools/i18n/LocalizedLabel';
import { Url } from '../../../Tools/Url';
import { Popup } from '../page/popup';
import ServiceAPI from '../../api/service.api';
const { ccclass, property } = _decorator;

@ccclass('LotteryPage')
export class LotteryPage extends BasePopUp<typeof Popup, { type: string, value: number }> {
    protected default_return: { type: string; value: number; };
    private ui_container: UITransform;

    @property(Node)
    background: Node = null;
    @property(Node)
    wardcontainer: Node = null;
    @property(Node)
    wardNodeArr: Node[] = [];
    wardTypeArr: number[] = [31, 2, 4, 11, 3, 2, 4, 1];
    @property(Node)
    lottreward: Node = null;
    @property(Node)
    toucher: Node = null;
    @property(Label)
    lottBtnConLabel: Label = null;
    @property(Label)
    downConLabel: Label = null;

    curAwardType: number = 0;
    curAwardNum: number = 0;
    curAwardAmount: number = 0;

    @property(Node)
    shan: Node = null;

    @property(Node)
    closeBtn: Node = null;

    @property(Node)
    lottBtn: Node = null;


    public pageConfig: { lotteryResults: { awardType: number; awardNum: number; awardAmount: number; }; cashTotal: number; } = null;

    public onShow(config: any) {

    }

    protected onEnable(): void {
        mtec.cc.adaptBackgroundNode(this.background, director.getScene().getChildByName('Canvas'));
        // console.log(this.pageConfig);
        this.renderLocalUI();

    }

    private __lottery_config_cache__: ReturnType<typeof ServiceAPI.LotteryConfig>;

    async retryLotteryConfig(userId: number, retries: number = 3) {
        let attempt = 0;
        let config = null;
        while (attempt < retries) {
            try {
                config = await ServiceAPI.LotteryConfig(userId);

                if (config?.cashTotal !== undefined) {
                    this.__lottery_config_cache__ = config;
                    return config;
                } else {
                    this.__lottery_config_cache__ = config;
                    console.warn("LotteryConfig 返回空值或 cashTotal 未定义");
                }
            } catch (error) {
                console.error(`LotteryConfig 请求失败 (第 ${attempt + 1} 次):`, error);
            }
            attempt++;
            // 等待一段时间后重试（可以根据需求增加延迟）
            await new Promise(resolve => setTimeout(resolve, 1000)); // 延迟 1 秒
        }
        if (!this.__lottery_config_cache__) {
            let con = {
                lotteryResults: {
                    awardType: 3,
                    awardNum: 1,
                    awardAmount: 0,
                },
                cashTotal: UserData.data.curCashTotal
            }
            return con
        }
        return this.__lottery_config_cache__;
    }

    protected _click_event_: { [name: string]: (this: LotteryPage, button: Button) => void; } = {
        async lottBtn(btn) {
            AudioMgr.ins.playOneShot(Url.AUDIO.SFX2, 1);
            let config = await this.retryLotteryConfig(UserData.data.userId);
            this.pageConfig = config;
            this.lottBtn.getChildByName('lottBtnM').active = true;
            this.lottBtn.getChildByName('lottBtnY').active = false;
            if (UserData.data.curlotteryChance > 0) {
                AudioMgr.ins.playEff(Url.AUDIO.SFX10);
                btn.interactable = false;
                this.closeBtn.active = false;
                UserData.data.curlotteryTimes++;
                UserData.data.curlotteryChance--;
                UIMgr.ins.stopLotteryIconScaleAnim();
                this.renderLocalUI();
                this.lotteringGetWard(this.pageConfig.lotteryResults.awardType, btn);
            } else {
                this.lottBtn.getChildByName('lottBtnM').active = false;
                this.lottBtn.getChildByName('lottBtnY').active = true;
                UIMgr.ins.createOneTipToast('game_toast_text1', this.needPassLevelTimes())
            }

        }
    }


    start() {

    }

    update(deltaTime: number) {

    }


    showRewardPage(awardType, awardNum, awardAmount) {
        this.curAwardType = awardType;
        this.curAwardNum = awardNum;
        this.curAwardAmount = awardAmount;
        this.lottreward.active = true;
        BasePopUp.jelly_enter(this.lottreward);
        tween(this.shan)
            .by(6, { angle: 360 })
            .repeatForever()
            .start()
        let awardchildren = this.lottreward.getChildByName('award').children
        if (awardType == 7) {
            for (let i = 0; i < awardchildren.length; i++) {
                awardchildren[i].active = false
            }
            awardchildren[1].active = true;
            this.lottreward.getChildByName("Label").getComponent(Label).string = "x" + awardNum.toString();
        } else if (awardType == 8) {
            for (let i = 0; i < awardchildren.length; i++) {
                awardchildren[i].active = false
            }
            awardchildren[2].active = true;
            this.lottreward.getChildByName("Label").getComponent(Label).string = "x" + awardNum.toString();
        } else {
            for (let i = 0; i < awardchildren.length; i++) {
                awardchildren[i].active = false
            }
            awardchildren[0].active = true;
            this.lottreward.getChildByName('Label').getComponent(Label).string = UIMgr.ins.formatCashValue(awardAmount);
        }



    }

    shuffleArray<T>(array: T[]): T[] {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
    }

    renderLocalUI() {
        for (let i = 0; i < this.wardNodeArr.length; i++) {
            let ward = this.wardNodeArr[i];
            ward.getComponent(Sprite).color = Color.WHITE;
        }
        // this.wardNodeArr[0].getComponent(Sprite).color = Color.YELLOW;
        // console.log(UserData.data.curlotteryChance);

        if (UserData.data.curlotteryChance > 0) {
            this.lottBtnConLabel.node.parent.active = true;
            this.toucher.active = true;
            tween(this.toucher)
                .to(0.2, { scale: v3(1.2, 1.2, 1) })
                .to(0.2, { scale: v3(1, 1, 1) })
                .union()
                .repeatForever()
                .start();
            let localizedLabel = this.lottBtnConLabel.node.getComponent(LocalizedLabel);
            localizedLabel.setTextKeyAndOption("pop_lotterypage_cond2_text", UserData.data.curlotteryChance);
        } else {
            // this.lottBtnConLabel.node.parent.active = false;
            let localizedLabel = this.lottBtnConLabel.node.getComponent(LocalizedLabel);
            localizedLabel.setTextKeyAndOption("pop_lotterypage_cond2_text", UserData.data.curlotteryChance);
            this.toucher.active = false;
        }

        let needPassTimes = this.needPassLevelTimes();
        let localizedLabel1 = this.downConLabel.node.getComponent(LocalizedLabel);
        localizedLabel1.setTextKeyAndOption("pop_lotterypage_cond_text", needPassTimes);

    }

    /** 获得抽奖所需通关数量 */
    public needPassLevelTimes() {
        if(!GameData.data.drawProcessConfig){
            ServiceAPI.ConfCommon(UserData.data.userId)
            .then(ConfCommon=>{
                UserData.data.passLevelTimes = ConfCommon?.eliminateTotal;
                UserData.data.drawTotal = ConfCommon?.drawTotal;
                GameData.data.forceConfig = ConfCommon?.forceConfig;
                GameData.data.drawProcessConfig = ConfCommon?.drawProcessConfig;
            });
            return void 0;
        }
        const curLotteryTimes = UserData.data.curGetLotteryTimes;
        let needLevelTimes;
        // console.log(curLotteryTimes);
        for (let rule of GameData.data.drawProcessConfig) {
            if (curLotteryTimes >= rule.startCount && curLotteryTimes <= rule.endCount) {
                needLevelTimes = rule.skipCount - UserData.data.tempPassLevelTimes_lottery;
                break;
            }
        }
        return needLevelTimes;
    }

    lotteringGetWard(getWardType: number, btn: Button, initialInterval: number = 0.3, speedupFactor: number = 0.9, slowdownFactor: number = 1.8) {
        const totalNodes = this.wardNodeArr.length; // 8 个节点
        let currentIndex = 0;  // 当前变色节点的下标
        let cycleCount = 0;  // 当前循环次数
        const maxCycles = 4;  // 需要循环四次
        let targetIndex = this.wardTypeArr.indexOf(getWardType); // 找到目的节点的下标
        // console.log('targetIndex', targetIndex);

        if (targetIndex === -1) {
            console.error("Invalid getWardType value.");
            return;
        }

        const highlightNode = (index: number) => {
            // 依次将当前节点变为黄色，其他节点变为白色
            for (let i = 0; i < totalNodes; i++) {
                const sprite = this.wardNodeArr[i].getComponent(Sprite);
                if (i === index) {
                    sprite.color = Color.YELLOW;
                    if (i == 2 || i == 6) {
                        this.wardNodeArr[i].getChildByName('cash').getChildByName('ward').active = true;
                    }
                } else {
                    sprite.color = Color.WHITE;
                    if (i == 2 || i == 6) {
                        this.wardNodeArr[i].getChildByName('cash').getChildByName('ward').active = false;
                    }
                }
                // sprite.color = i === index ? Color.YELLOW : Color.WHITE;
            }
        };

        const loopNodes = (interval: number, speedupFactor: number, slowdownFactor: number, onComplete: Function) => {
            const loop = () => {
                // 检查是否需要停止在目标节点
                if (cycleCount >= maxCycles && currentIndex === targetIndex) {
                    highlightNode(currentIndex); // 在判断后高亮目标节点
                    onComplete();  // 完成循环后停在目标节点
                    return;
                }

                highlightNode(currentIndex);  // 高亮当前节点

                // 增加 index
                currentIndex = (currentIndex + 1) % totalNodes;  // 更新 currentIndex

                // 如果到了第三次循环，逐渐减慢
                if (cycleCount >= 2 && currentIndex === 0) {
                    interval *= slowdownFactor;  // 第三次循环开始减速
                } else if (cycleCount < 2) {
                    // 前两次循环逐渐加速
                    interval *= speedupFactor;
                }

                // 检查循环次数
                if (currentIndex === 0) {
                    cycleCount++;
                }

                setTimeout(loop, interval * 1000);  // 按指定间隔继续循环
            };
            loop();  // 启动循环
        };

        const onComplete = () => {
            // console.log("Stopped at target node:", targetIndex);
            AudioMgr.ins.stopPlayEff(Url.AUDIO.SFX10);
            this.lottBtn.getChildByName('lottBtnM').active = false;
            this.lottBtn.getChildByName('lottBtnY').active = true;

            btn.interactable = true;
            this.closeBtn.active = true;
            let config = {
                awardType: this.pageConfig.lotteryResults.awardType,
                needPassLevel: this.needPassLevelTimes(),
                awardAmount: this.pageConfig.lotteryResults.awardAmount,
                awardNum: this.pageConfig.lotteryResults.awardNum,
                cashTotal: this.pageConfig.cashTotal
            }
            this.scheduleOnce(() => {
                this.closePage();
                GameMgr.ins.resetTimer();
                GameMgr.ins.getElimitateCash();
                Popup.Getlottwardpage(config);
            }, 1)

        };

        // 执行前两次逐渐加快的循环，然后第三次逐渐减慢
        loopNodes(initialInterval, speedupFactor, slowdownFactor, onComplete);
    }

    closePage() {
        AudioMgr.ins.playOneShot(Url.AUDIO.SFX2, 1);
        this.node.active = false;
        GameMgr.ins.startTimer();
    }

}

